package com.fastgwt.client.mvc.controller;

import com.fastgwt.client.mvc.model.EmployeeModel;
import com.fastgwt.client.mvc.view.EmployeeEditor;
import com.fastgwt.client.mvc.view.EmployeeView;
import com.fastgwt.shared.dto.Employee;
import com.fastgwt.shared.mvctemplate.controller.GwtController;
import com.fastgwt.shared.services.EmployeeService;
import com.fastgwt.shared.services.EmployeeServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.sencha.gxt.widget.core.client.box.MessageBox;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler;
import com.sencha.gxt.widget.core.client.info.Info;

public class EmployeeController extends GwtController<Employee> {

	private EmployeeServiceAsync employeeService;

	interface EmployeeDriver extends
			SimpleBeanEditorDriver<Employee, EmployeeEditor> {
	}

	private EmployeeDriver driver;

	public EmployeeController() {

		model = new EmployeeModel();
		view = new EmployeeView();

		addHandlersToView((EmployeeView) view);

		employeeService = (EmployeeServiceAsync) GWT
				.create(EmployeeService.class);
		driver = GWT.create(EmployeeDriver.class);
		driver.initialize(((EmployeeView) getView()).getEmployeeEditor());
		driver.edit(new Employee());
	}

	private void addHandlersToView(final EmployeeView view) {

		view.btnSave.addSelectHandler(new SelectHandler() {

			@Override
			public void onSelect(SelectEvent event) {
				Employee emp = new Employee();
				// emp.setEmployeeId(Long
				// .parseLong(view.getEmployeeId().getText()));
				// emp.setEmployeeName(view.getEmployeeName().getText());
				// emp.setEmployeeSurname(view.getEmployeeSurname().getText());
				// emp.setEmail(view.getEmail().getText());

				driver.flush();
				emp = driver.flush();
				Info.display("emp", emp.toString());
				if (driver.hasErrors()) {
					new MessageBox("Please correct the errors before saving.")
							.show();
					return;
				}
				employeeService.saveOrUpdateEmployee(emp,
						new AsyncCallback<Employee>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user

								Info.display("failed", "rpc is failed");
							}

							public void onSuccess(Employee emp) {
								Info.display("succes",
										"Employee is saved name " + emp);
							}
						});

			}
		});

	}

	public EmployeeDriver getDriver() {
		return driver;
	}

	public void setDriver(EmployeeDriver driver) {
		this.driver = driver;
	}

	public EmployeeServiceAsync getEmployeeService() {
		return employeeService;
	}

	public void setEmployeeService(EmployeeServiceAsync employeeService) {
		this.employeeService = employeeService;
	}
}
